package com.adk.backend.controller;

import com.adk.backend.common.Result;
import com.adk.backend.entity.LxAdmin;
import com.adk.backend.service.AuthService;
import com.adk.backend.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private PermissionService permissionService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        try {
            // 支持email和username两种字段名
            String email = loginRequest.get("email");
            if (email == null || email.isEmpty()) {
                email = loginRequest.get("username");
            }
            String password = loginRequest.get("password");
            
            if (email == null || email.isEmpty()) {
                return Result.error("邮箱或用户名不能为空");
            }
            if (password == null || password.isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            Map<String, Object> result = authService.login(email, password);
            if ((Boolean) result.get("success")) {
                return Result.success("登录成功", result);
            } else {
                return Result.error((String) result.get("message"));
            }
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户信息（包含权限信息）
     */
    @GetMapping("/userinfo")
    public Result<Map<String, Object>> getUserInfo(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            LxAdmin admin = authService.getUserByToken(token);
            if (admin != null) {
                // 构建用户信息（包含权限）
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", admin.getId());
                userInfo.put("username", admin.getUsername());
                userInfo.put("email", admin.getEmail());
                userInfo.put("userType", admin.getUserType());
                userInfo.put("customerId", admin.getCustomerId());
                userInfo.put("whId", admin.getWhId());
                userInfo.put("avatar", admin.getAvatar());
                
                // 获取用户权限信息
                Map<String, Object> permissions = permissionService.getUserPermissions(admin.getUserType());
                userInfo.put("permissions", permissions);
                
                return Result.success(userInfo);
            }
            return Result.error("未登录或Token已过期");
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error("获取用户信息失败");
        }
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Boolean> logout(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            authService.logout(token);
            return Result.success("退出成功", true);
        } catch (Exception e) {
            log.error("退出登录失败", e);
            return Result.error("退出登录失败");
        }
    }
    
    /**
     * 获取业务员列表（user_type in (4, 6, 35) 且 status=0）
     */
    @GetMapping("/sales-users")
    public Result<List<LxAdmin>> getSalesUsers() {
        try {
            List<LxAdmin> salesUsers = authService.getSalesUsers();
            return Result.success(salesUsers);
        } catch (Exception e) {
            log.error("获取业务员列表失败", e);
            return Result.error("获取业务员列表失败：" + e.getMessage());
        }
    }
}

